package com.ccb.sc.member.service;

import com.ccb.sc.member.vo.ReceiverCreateVo;
import com.ccb.sc.member.vo.ReceiverVo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ccb.sc.member.convert.ReceiverConvert;
import com.ccb.sc.common.modules.member.entity.Receiver;
import com.ccb.sc.common.modules.member.mapper.ReceiverMapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

import java.util.List;

/**
 * <p>
 * 收货地址 服务实现类
 * </p>
 *
 * @author ken
 * @since 2020-09-25
 */
@Service
public class ReceiverService extends ServiceImpl<ReceiverMapper, Receiver> {

    public List<ReceiverVo> findAll(Long memberId) {
        List<Receiver> list = this.list(new QueryWrapper<Receiver>().lambda()
                .eq(Receiver::getMemberId, memberId)
                .orderByDesc(Receiver::getIsDefault)
                .orderByDesc(Receiver::getModifyTime));
        return ReceiverConvert.INSTANCE.entity2ListItemBatch(list);
    }

    @Transactional(rollbackFor = Exception.class)
    public boolean createNew(Long memberId, ReceiverCreateVo createVo) {
        Receiver receiver = ReceiverConvert.INSTANCE.createParam2Entity(createVo);
        receiver.setMemberId(memberId);
        if (receiver.getIsDefault()) {
            this.getBaseMapper().removeDefault(memberId);
        }
        return this.save(receiver);
    }

    public boolean update(Long memberId, ReceiverVo updateVo) {
        // 校验收货地址
        this.validReceiver(memberId, updateVo.getId());
        Receiver receiver = ReceiverConvert.INSTANCE.updateParam2Entity(updateVo);
        receiver.setMemberId(memberId);
        if (receiver.getIsDefault()) {
            this.getBaseMapper().removeDefault(memberId);
        }
        return this.updateById(receiver);
    }

    public boolean delete(Long memberId, Long id) {
        // 校验收货地址
        this.validReceiver(memberId, id);
        return this.removeById(id);
    }

    @Transactional(rollbackFor = Exception.class)
    public boolean setDefault(Long memberId, Long id) {
        Receiver receiver = this.validReceiver(memberId, id);
        if (receiver.getIsDefault()) {
            return true;
        }

        this.getBaseMapper().removeDefault(memberId);
        receiver.setIsDefault(true);
        return this.updateById(receiver);
    }

    /**
     * 校验收货地址
     * @param memberId 会员id
     * @param id 收货地址记录id
     * @return Receiver
     */
    private Receiver validReceiver(Long memberId, Long id) {
        Receiver receiver = this.getById(id);
        Assert.notNull(receiver, "未找到收货地址信息");
        Assert.isTrue(memberId.equals(receiver.getMemberId()), "未找到收货地址信息");
        return receiver;
    }
}
